package com.kamistoat.meimeimall.meimeimallseckill.web;

import com.kamistoat.meimeimall.common.To.seckillTo.SecKillProductCacheTo;
import com.kamistoat.meimeimall.common.annotation.DubboAndHTTPExceptionCatch;
import com.kamistoat.meimeimall.common.utils.R;
import com.kamistoat.meimeimall.meimeimallseckill.service.SeckillSessionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "商品详情页操作")
@RestController
@RequestMapping("web")
public class ProductPageController {

    @Autowired
    SeckillSessionService seckillSessionService;

    /**
     * 带缓查询当前商品的秒杀活动
     *
     * @param skuId skuId
     */
    @ApiOperation("查询当前商品是否存在秒杀活动，或者未来的秒杀活动")
    @GetMapping("/sku_current_session/{skuId}")
    @DubboAndHTTPExceptionCatch
    public R getSkuCurrentSession(@PathVariable("skuId") Long skuId) {
        SecKillProductCacheTo skuInSession = seckillSessionService.getSkuInSession(skuId);
        return R.ok().put("skuInSession", skuInSession);
    }


    /**
     * 前端直接点击秒杀商品的 '立即抢购'，发送请求给次链接。
     * 直接验证信号量。如果通过则进入下单阶段，如果不通过则拦截。
     * 此处是唯一直面全部流量的地方，通过信号量机制，限制大部分流量，保证后序只有少量流量通过。
     */
    @ApiOperation("前端直接点击购买秒杀商品")
    @GetMapping("/seckill_product_click")
    @DubboAndHTTPExceptionCatch
    public R secKillProduct(@RequestParam Long sessionId,
                            @RequestParam String randomCode,
                            @RequestParam Long skuId,
                            @RequestParam Integer num) {
        seckillSessionService.secKillProduct(sessionId, randomCode, skuId, num);
        String redirectPath = "redirect:meimeimallorder/web/seckill_to_order_check?" +
                "sessionId=" + sessionId.toString() +
                "&randomCode=" + randomCode +
                "&skuId=" + skuId.toString() +
                "&num=" + num.toString();
        return R.ok("秒杀商品库存校验成功，放行请求").put("redirectPath", redirectPath);
    }
}
